<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>

<body>
    <script>
        // 模拟 localStorage 时如何实现过期时间功能
        let obj = {// 存到这里面
            cc: {},
            setItem: function (key, value, time) {
                this.cc[key] = value
                if(time) {
                    setTimeout(()=>{
                        this.removeItem(key)
                    },time)
                }
            },
            getItem: function (key) {
                return this.cc[key] || null
            },
            removeItem: function (key) {
                delete this.cc[key]
            },
            clear() {
                this.cc = {}
            }
        }
        obj.setItem('time','时间啊时间',3000)
        console.log(obj.getItem('time'))
        setTimeout(()=>{
        console.log(obj.getItem('time'))

        },4000)
        // 另一种写法
        const cd = (function () {
            let cc = {}       // 存到这里面
            return {
                setItem: function (key, value,time){
                    cc[key] = value
                    if(time) {
                        console.log(typeof time)
                        if(typeof time !='number') throw '时间必须为数字'
                        setTimeout(res=>{
                            this.removeItem(key)
                        })
                    }
                
                }
                ,
                getItem: (key) => cc[key] || null,
                removeItem: (key) => delete cc[key],
                clear: () => cc = {}
            }
        })()
        Object.defineProperty(Object.prototype, 'my', {
            value:cd
        })
        let ddd = '哇咔咔'
        let zzz = 'zzzzz'
        my.setItem('xx', ddd)
        my.setItem('zzz', zzz,2000)
        console.log(my.getItem('xx'))
        my.removeItem('xx')
        console.log(my.getItem('xx'))
        console.log(my.getItem('zzz'))
        my.clear()
        console.log(my.getItem('zzz'))
       setTimeout(res=>{
        console.log(my.getItem('zzz'))
       },4000)
    </script>
</body>

</html>